/*
 * Copyright 2009 Johnson Consulting Services
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * 
 */
package com.johnsoncs.gwt.application.client.validation.constraints;

import static com.johnsoncs.gwt.application.client.validation.ValidationState.parameters;

import com.johnsoncs.gwt.application.client.validation.Constraint;
import com.johnsoncs.gwt.application.client.validation.ValidationContext;
import com.johnsoncs.gwt.application.client.validation.ValidationState;
import com.johnsoncs.gwt.application.client.validation.ValidationValue;
import com.johnsoncs.gwt.application.client.validation.ValidationState.Severity;
import com.johnsoncs.gwt.widgets.client.util.Callback;

/**
 * @author wilj
 *
 */
@SuppressWarnings("unchecked")
public class RangeConstraint implements Constraint {
	private final Comparable minValue;
	private final Comparable maxValue;

	/**
	 * @param minValue
	 * @param maxValue
	 */
	public RangeConstraint(final Comparable minValue, final Comparable maxValue) {
		super();
		this.minValue = minValue;
		this.maxValue = maxValue;
	}

	/* (non-Javadoc)
	 * @see com.johnsoncs.gwt.application.client.validation.Constraint#applyTo(com.johnsoncs.gwt.application.client.validation.ValidationValue, com.johnsoncs.gwt.application.client.validation.ValidationContext, com.johnsoncs.gwt.widgets.client.util.Callback)
	 */
	@Override
	public void applyTo(final ValidationValue value, final ValidationContext context,
			final Callback<ValidationState> callback) {
		final Comparable c = value.getValue();
		if (c != null && (c.compareTo(minValue) == -1 || c.compareTo(maxValue) == 1)) {
			callback.exec(new ValidationState("outOfRange", Severity.ERROR, value.getQueryPath(),
					parameters("minValue", minValue, "maxMaxValue", maxValue)));
		} else {
			callback.exec(null);
		}
	}

}
